<?php

namespace app\admin\model;

use app\model\Model;

class Upload extends Model
{
  public $img_allow, $file_allow, $media_allow, $accepted_origins, $img_dir, $file_dir, $media_dir;
  public $water_img = './uploadfile/water.png';

  function __construct()
  {
    require('check.php'); // 检查管理员登陆状态
    new Check();

    $this->img_allow = str_array(IMG_EXT, ',');
    $this->file_allow = str_array(FILE_EXT, ',');
    $this->media_allow = str_array(MEDIA_EXT, ',');
    $this->accepted_origins = str_array(UPLOAD_ACCEPT, ',');
    $this->img_dir = './uploadfile/image/' . date('Ymd') . '/';
    $this->file_dir = './uploadfile/file/' . date('Ymd') . '/';
    $this->media_dir = './uploadfile/media/' . date('Ymd') . '/';

    if (isset($_SERVER['SERVER_NAME'])) {

      // 验证来源是否在白名单内
      if (in_array($_SERVER['SERVER_NAME'], $this->accepted_origins) || !UPLOAD_ACCEPT_ON) {
        header('Access-Control-Allow-Origin: ' . $_SERVER['SERVER_NAME']);
        return;
      }
      header("HTTP/1.1 403 Origin Denied");
      exit;
    }
  }

  function index()
  {
  }

  function trans($data)
  {
    $data['path'] = preg_replace(array('/(\.\.\\\\)+/', '/\\\\/'), '/', $data['path']);
    return $data;
  }

  function image()
  {
    require_once(LIB_PATH . "cls.plupload.php");

    if (!file_exists($this->img_dir)) {
      mkdir($this->img_dir);
    }

    $ph = new \PluploadHandler(array(
      'target_dir' => $this->img_dir,
      'allow_extensions' => array_str($this->img_allow, ',')
    ));

    $ph->sendNoCacheHeaders();
    $ph->sendCORSHeaders();

    if ($result = $ph->handleUpload()) {
      $res = $this->trans($result);
      admin_log('图片上传 [' . $res['path'] . ']');

      die(json_encode(array(
        'OK' => 1,
        'info' => $res,
        'location' => $res['path']
      )));
    }

    die(json_encode(array(
      'OK' => 0,
      'error' => array(
        'code' => $ph->getErrorCode(),
        'message' => $ph->getErrorMessage()
      )
    )));
  }

  function file()
  {
    require_once(LIB_PATH . "cls.plupload.php");

    if (!file_exists($this->file_dir)) {
      mkdir($this->file_dir);
    }

    $ph = new \PluploadHandler(array(
      'target_dir' => $this->file_dir,
      'allow_extensions' => array_str($this->file_allow, ',')
    ));

    $ph->sendNoCacheHeaders();
    $ph->sendCORSHeaders();

    if ($result = $ph->handleUpload()) {
      $res = $this->trans($result);
      admin_log('文件上传 [' . $res['path'] . ']');

      die(json_encode(array(
        'OK' => 1,
        'info' => $res,
        'location' => $res['path']
      )));
    }

    die(json_encode(array(
      'OK' => 0,
      'error' => array(
        'code' => $ph->getErrorCode(),
        'message' => $ph->getErrorMessage()
      )
    )));
  }

  function media()
  {
    require_once(LIB_PATH . "cls.plupload.php");

    if (!file_exists($this->media_dir)) {
      mkdir($this->media_dir);
    }

    $ph = new \PluploadHandler(array(
      'target_dir' => $this->media_dir,
      'allow_extensions' => array_str($this->media_allow, ',')
    ));

    $ph->sendNoCacheHeaders();
    $ph->sendCORSHeaders();

    if ($result = $ph->handleUpload()) {
      $res = $this->trans($result);
      admin_log('媒体上传 [' . $res['path'] . ']');

      die(json_encode(array(
        'OK' => 1,
        'info' => $res,
        'location' => $res['path']
      )));
    }

    die(json_encode(array(
      'OK' => 0,
      'error' => array(
        'code' => $ph->getErrorCode(),
        'message' => $ph->getErrorMessage()
      )
    )));
  }

  /*
  function tinyimage()
  {
    require_once(LIB_PATH . 'cls.image.php');

    if (!file_exists($this->img_dir)) {
      mkdir($this->img_dir);
    }

    reset($_FILES);
    $temp = current($_FILES);

    if (!is_uploaded_file($temp['tmp_name'])) {
      // 通知编辑器上传失败
      header("HTTP/1.1 500 Server Error");
      exit;
    }

    // 如果脚本需要接收cookie，在init中加入参数 images_upload_credentials : true
    // 并加入下面两个被注释掉的header内容
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // 简单的过滤一下文件名是否合格
    if (preg_match("/([^\w\s\d\-_~,;:\.\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
      header("HTTP/1.1 400 Invalid file name.");
      exit;
    }

    // 验证扩展名
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), $this->img_allow)) {
      header("HTTP/1.1 400 Invalid extension.");
      exit;
    }

    // 都没问题，就将上传数据移动到目标文件夹，此处直接使用原文件名，建议重命名
    //获得文件扩展名
    $temp_arr = explode(".", $temp['name']);
    $file_ext = array_pop($temp_arr);
    $file_ext = trim($file_ext);
    $file_ext = strtolower($file_ext);
    $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
    $filetowrite = $this->img_dir . $new_file_name;
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    @chmod($filetowrite, 0644);

    // 压缩图片
    if (UPLOAD_LIMIT && !empty($_POST['ifWidthLimit'])) {
      $imgproc = new \Image_process($filetowrite);
      if ($imgproc->source_width > UPLOAD_IMG) {
        $imgproc->scaleImage(round(UPLOAD_IMG / $imgproc->source_width, 1));
      } else {
        unset($imgproc);
      }
    }

    // 水印
    if (!empty($_POST['ifWater'])) {
      $imgproc = new \Image_process($filetowrite);
      $imgproc->watermarkImage($this->water_img);
    }

    // 返回JSON格式的数据
    // 形如下一行所示，使用location存放图片URL
    // { location : '/your/uploaded/image/file.jpg'}
    // 相对admin转站点目录
    $filetowrite = preg_replace('/(\.\.\/)+/i', '/', $filetowrite);
    echo json_encode(array('location' => $filetowrite));
  }

  function tinyfile()
  {
    if (!file_exists($this->file_dir)) {
      mkdir($this->file_dir);
    }

    reset($_FILES);
    $temp = current($_FILES);
    if (!is_uploaded_file($temp['tmp_name'])) {
      // 通知编辑器上传失败
      header("HTTP/1.1 500 Server Error");
      exit;
    }

    // 如果脚本需要接收cookie，在init中加入参数 images_upload_credentials : true
    // 并加入下面两个被注释掉的header内容
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // 简单的过滤一下文件名是否合格
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
      header("HTTP/1.1 400 Invalid file name.");
      exit;
    }

    // 验证扩展名
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), $this->file_allow)) {
      header("HTTP/1.1 400 Invalid extension.");
      exit;
    }

    // 都没问题，就将上传数据移动到目标文件夹，此处直接使用原文件名，建议重命名
    //获得文件扩展名
    $temp_arr = explode(".", $temp['name']);
    $file_ext = array_pop($temp_arr);
    $file_ext = trim($file_ext);
    $file_ext = strtolower($file_ext);
    $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
    $filetowrite = $this->file_dir . $new_file_name;
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    @chmod($filetowrite, 0644);

    // 返回JSON格式的数据
    // 形如下一行所示，使用location存放图片URL
    // { location : '/your/uploaded/image/file.jpg'}
    // 相对admin转站点目录
    $filetowrite = preg_replace('/(\.\.\/)+/i', '/', $filetowrite);
    echo json_encode(array('location' => $filetowrite));
  }
  */

  function __destruct()
  {
  }
}